/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import com.bourre.core.HashCodeFactory;
import com.bourre.data.libs.AbstractLib;
import com.bourre.data.libs.ConfigLoader;
import com.bourre.data.libs.ConfigLoaderEvent;
import com.bourre.data.libs.XMLToObjectDeserializer;
import com.bourre.events.StringEvent;
import com.bourre.ioc.plugin.AbstractPlugin;
import com.bourre.utils.ClassUtils;

import fever.conf.ParserQueue;
import fever.conf.ParserQueueListener;
import fever.exception.IllegalAccessException;
import fever.Fever;
import fever.ioc.conf.CoreConfiguration;
import fever.ioc.conf.parsers.BitmapParser;
import fever.ioc.conf.parsers.LocalisationParser;
import fever.ioc.conf.PluginConfiguration;
import fever.ioc.plugin.PluginLocalisation;
import fever.utils.Stringifier;
import fever.utils.StringUtil;

/**
 * Extends <strong>PixIOC AbstractPlugin</strong> to add <strong>Fever</strong> 
 * features.
 * 
 * <ul>
 *   <li>Configuration API</li>
 *   <li>Localisation API</li>
 * </ul>
 * 
 * @author Romain Ecarnot
 */
class fever.ioc.plugin.FeverPlugin extends AbstractPlugin 
	implements ParserQueueListener
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private var _parser : ParserQueue;
	private var _sName : String;
	private var _oConfig : PluginConfiguration;
	private var _oLocalPlugin : PluginLocalisation;
	private var _bConfigLoaded : Boolean;	
	
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
	
	/** Default name for configuration file. */
	public static var PLUGIN_CONFIGURATION_FILE : String = 'config.xml';
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns translation of passed-in {@code id} resource using 
	 * localisation API.
	 * 
	 * <p>Shortcut for 
	 * {@link fever.ioc.plugin.PluginLocalisation#getResourceAsString} method.
	 * 
	 * @param id Resource identifer to translate.
	 */
	public function getTranslation( id : String ) : String
	{
		return String( _oLocalPlugin.getResourceAsString( id ) );
	}
	
	/**
	 * Returns plugin localisation instance.
	 */
	public function getLocalisation( ) : PluginLocalisation
	{
		return _oLocalPlugin;	
	}
	
	/**
	 * Returns plugin configuration object.
	 */
	public function getConfig(  ) : PluginConfiguration
	{
		return _oConfig;
	}
	
	/**
	 * Returns plugin name ( eq : Main plugin class name ).
	 */
	public function getName(  ) : String
	{
		return _sName;
	}
	
	/**
	 * Returns plugin name + hashcode.
	 * 
	 * @see getName
	 */
	public function getHashCodeName(  ) : String
	{
		return _sName + ' [ ' + HashCodeFactory.getKey( this ) + ' ]';
	}
	
	/**
	 * Returns plugin repository path.
	 */
	public function getPluginPath(  ) : String 
	{
		return CoreConfiguration.pluginRepository;
	}
	
	/**
	 * Returns plugin configuration path.
	 */
	public function getConfigPath(  ) : String 
	{
		return getPluginPath() + _sName + '/';	
	}
	
	/**
	 * Returns {@code true} is configuration file is correctly loaded 
	 * and parsed.
	 */
	public function isConfigLoaded(  ) : Boolean
	{
		return _bConfigLoaded;
	}
	
	/**
	 * Must be override by own plugin class.
	 * 
	 * <p>Trigger automatically by <strong>Fever</strong> engine when 
	 * plugin is ready and loaded.
	 */
	public function run( ) : Void
	{
		throw new IllegalAccessException( this + '#run() must be overrides' );	
	}
	
	/**
	 * Returns string representation.
	 */
	public function toString() : String
	{
		return Stringifier.parse( this );
	}
	
	/**
	 * Triggered when {@link fever.conf.ParserQueue} starts parsing.
	 */
	public function onParsingStart( event : StringEvent ) : Void
	{
		Fever.application.setTitle( null, event.getString() );
	}

	/**	
	 * Triggered when {@link fever.conf.ParserQueue} dequeues a new parser.
	 */
	public function onParsingChange( event : StringEvent ) : Void
	{
		Fever.application.setTitle( null, event.getString() );
	}
	
	/**
	 * Triggered when {@link fever.conf.ParserQueue} process is complete.
	 */
	public function onParsingComplete( event : StringEvent ) : Void
	{
		_onConfigComplete( );
		
		Fever.application.setTitle( null, '' );
	}
	
	/**
	 * Triggered during LibParser progression. 
	 */
	public function onParsingProgress( event : StringEvent ) : Void
	{
		Fever.application.setTitle( null, event.getString() );
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
		
	/**
	 * Constructor.
	 * 
	 * @param loadConfig {@code true} to enable configuration loading
	 */ 
	private function FeverPlugin( loadConfig : Boolean ) 
	{
		super();
		
		
		//Retreive real plugin name
		_sName = ClassUtils.getClassName( this );
		
		//Creates plugin localistion object
		_oLocalPlugin = PluginLocalisation.getInstance( this );
		
		_bConfigLoaded = false;
		
		_processConfiguration( loadConfig );
	}
	
	/**
	 * Starts loading, or not, plugin configuration.
	 * 
	 * @param enabled {@code true} to load configuration
	 */
	private function _processConfiguration( enabled : Boolean ) : Void 
	{
		if ( enabled ) _loadConfig();
		else run();	
	}
	
	/**
	 * Overrides to custom xml config file url.
	 */
	private function _getConfigFilePath(  ) : String 
	{
		return ( getConfigPath() + PLUGIN_CONFIGURATION_FILE );
	}
	
	/**
	 * Overrides to custom configuration parser.
	 */
	private function _buildParser(  ) : Void 
	{
		_parser.addType( new LocalisationParser( this ) );
		_parser.addType( new BitmapParser( this ) );
	}
	
	/**
	 * Starts configuration process.
	 */
	private function _loadConfig(  ) : Void 
	{
		_parser = new ParserQueue();
		_buildParser();
		_parser.addListener( this );
		
		XMLToObjectDeserializer.DESERIALIZE_ATTRIBUTES = true;
		XMLToObjectDeserializer.PUSHINARRAY_IDENTICAL_NODE_NAMES = true;
		
		_oConfig = new PluginConfiguration( getConfigPath() );
		
		var cLoader : AbstractLib = _getConfigLoader( _oConfig );
		cLoader.setAntiCache( true );
		cLoader.setTimeOut( 1000 );
		cLoader.addEventListener( 
			AbstractLib.onLoadInitEVENT, 
			this, 
			_onConfigLoaded 
		);		cLoader.addEventListener( 
			AbstractLib.onErrorEVENT, 
			this, 
			_onConfigError 
		);		cLoader.addEventListener( 
			AbstractLib.onTimeOutEVENT, 
			this, 
			_onConfigError 
		);
		
		cLoader.load( _getConfigFilePath() );
	}
	
	/**
	 * Returns basic config loader as {@code null} is passed to 
	 * constructor.
	 * 
	 * <p>Override to enable custom or secure config loading.
	 */
	private function _getConfigLoader( object : Object ) : AbstractLib 
	{
		return new ConfigLoader( object );
	}
	
	/**
	 * Triggered when configuration file is loaded.
	 * 
	 * <p>Starts configuration parsing.
	 */
	private function _onConfigLoaded( event : ConfigLoaderEvent ) : Void 
	{
		event.getLib().release();
		
		getConfig().localeURL = _trimUrlPath( getConfig().paths.localeURL.value );
		getConfig().fontURL = _trimUrlPath( getConfig().paths.fontURL.value );
		getConfig().dllURL = _trimUrlPath( getConfig().paths.dllURL.value );
		getConfig().bitmapURL = _trimUrlPath( getConfig().paths.bitmapURL.value );
		getConfig().soundURL = _trimUrlPath( getConfig().paths.soundURL.value );
		
		_parser.execute();
	}
	
	/**
	 * Triggered when configuration file is not loaded.
	 */
	private function _onConfigError( event : ConfigLoaderEvent ) : Void 
	{
		getLogger().fatal( getName() + ' loading configuration error' );
		
		run();
	}
	
	/**
	 * Triggered when configuration file is parsed.
	 * 
	 * <p>Starts application calling {@link #run()} method.
	 */
	private function _onConfigComplete( ) : Void 
	{
		_bConfigLoaded = true;
		
		run();
	}
	
	/**
	 * Builds and returns clean relative path.
	 */
	private function _trimUrlPath( s : String ) : String
	{
		var r : String = StringUtil.finishWithChar( s, '/', true );
		r = StringUtil.leftTrim( s, StringUtil.EMPTY_CHARS + '/' );
		return ( r ) ? ( r + '/' ) : '';
	}
}